# How to install Apache, MariaDB, PHP, PhpMyAdmin (AMPP) on FreeBSD

Instructions tested on NomadBSD version 1.4 [FreeBSD 12.2-p4 based] on amd64. Also has been tested on DragonFly v5.8.3-RELEASE with slight modifications (indicated where necessary).

**WARNING:** This guide has been prepared for desktop use in mind and not for security or servers. If you need secure setups, refer to proper guides elsewhere. This is also based on FreeBSD which is not 100% Free Software and contains nonfree software. Using it may harm your user freedom.

**NOTE:** This guide is for testing purposes only. Production use is not recommended.

Doing a system upgrade before continuing is recommended:

```sh
sudo pkg update && sudo pkg upgrade -y ; sync
```

## Step 1: Install packages

Run `pkg search` and find the versioned packages to install:

```sh
pkg search apache
pkg search php
pkg search mariadb
pkg search phpmyadmin
```

For example:

```sh
sudo pkg install apache24 php80 mod_php80 mariadb104-server
```

_**NOTE:** The command above is presented as an example and may not work in future at some point. Also, throughout this guide, you'll need to change the version number after package names or directories depending on which version you install. Applies to `apache24`, `php80`, `mariadb104-server`_

At the time of writing this `mariadb105-server` package has the `my_print_defaults` file missing (`which my_print_defaults` returns empty). So, an [error](https://bugs.mysql.com/bug.php?id=57062) is shown: `FATAL ERROR: Could not find ./bin/my_print_defaults`. If this is happening to you, using `mariadb104-server` for the time being should fix the problem.

### Info: Handling services

These are some common service related tasks. These may help you troubleshoot config issues or just help you in using it. You may need to enable services on `/etc/rc.conf`, instructions for which are given later on.

Starting:

```sh
sudo service apache24 start
sudo service mysql-server start
```

Stopping:

```sh
sudo service apache24 stop
sudo service mysql-server stop
```

Restarting:

```sh
sudo service apache24 restart
sudo service mysql-server restart
```

## Step 3: Preparing

### Apache

We now create `httpd.conf` and `mime.types` from a sample. FreeBSD's Apache package also redirects to HTTPS for localhost by default, so we need to set it up as well: 

```sh
sudo cp /usr/local/etc/apache24/httpd.conf.sample /usr/local/etc/apache24/httpd.conf
sudo cp /usr/local/etc/apache24/mime.types.sample /usr/local/etc/apache24/mime.types
sudo cp /usr/local/etc/apache24/extra/httpd-ssl.conf.sample /usr/local/etc/apache24/Includes/httpd-ssl.conf
```

Now we prepare a separate file for our customizations. This should be easier to transfer when we upgrade Apache: 

`sudo nano /usr/local/etc/apache24/Includes/10-mychanges.conf`

```
# SSL
LoadModule ssl_module libexec/apache24/mod_ssl.so
LoadModule socache_shmcb_module libexec/apache24/mod_socache_shmcb.so
# To suppress startup warning message
ServerName localhost:80
# PHP
<IfModule php_module>
    DirectoryIndex index.html default.php index.php
    AddHandler application/x-httpd-php .php
</IfModule>
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
<FilesMatch "\.php$">
    SetHandler application/x-httpd-php
</FilesMatch>
<FilesMatch "\.phps$">
    SetHandler application/x-httpd-php-source
</FilesMatch>
# phpMyAdmin
Alias /phpmyadmin "/usr/local/www/phpMyAdmin/"

<Directory "/usr/local/www/phpMyAdmin/">
	Options None
	AllowOverride Limit

	Require local
	Require host localhost
</Directory>
```

On DragonFlyBSD you may need to add this at the top:

```
# DragonFlyBSD fix
DirectoryIndex index.html index.php
AddType text/html       php
```

Add your user as Apache user. (Precaution: Make sure `echo $USER` returns your normal username before running this):

```
echo -e "# Set current user as apache user\nUser $USER\nGroup $USER" | sudo tee /usr/local/etc/apache24/Includes/20-myuserperm.conf
```

### SSL

The sample `httpd-ssl.conf` has these paths below by default, so we're just going to keep our files on these locations to save us from editing stuff:

```
/usr/local/etc/apache24/server.crt
/usr/local/etc/apache24/server.key
```

Just run these to get SSL cert related files ready. These instructions will enable you to make it work on modern browsers without issues:

```sh
mkdir ~/cert
cd ~/cert
openssl genrsa -des3 -out myCA.key 2048
openssl req -x509 -new -nodes -key myCA.key -sha256 -days 825 -out myCA.pem
# Enter pass phrase. Be sure to remember or note it
# Enter Organization as something memorable, like ABC Ltd.
# Enter FQDN/Common name as localhost
openssl genrsa -out server.key 2048
openssl req -new -key server.key -out server.csr
# When asked for organization name, enter something like ABC Ltd. to identify it later.
# Enter FQDN/Common name as localhost. Press enter for other ones.
>server.ext cat <<-EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost # Be sure to include the domain name here because Common Name is not so commonly honoured by itself
IP.1 = 127.0.0.1 # Optionally, add an IP address (if the connection which you have planned requires it)
EOF
# Create the signed certificate
openssl x509 -req -in server.csr -CA myCA.pem -CAkey myCA.key -CAcreateserial \
  -out server.crt -days 825 -sha256 -extfile server.ext
```

Now we copy the `.crt` and `.key` file in place so that config can find it:

```sh
sudo cp -i server.crt /usr/local/etc/apache24/server.crt
sudo cp -i server.key /usr/local/etc/apache24/server.key
```

Keep the `myCA.pem` around. If you have any new browser, you can go to it's settings/preferences. search for "cert" and import the file as certificate authority. Afterwards, you'll get https on localhost (`https://localhost`) without any certificate errors. Due to hardening of modern browsers, this will have to be done on every browser you use.

To enable Apache service:

```sh
echo 'apache24_enable="yes"' | sudo tee -a /etc/rc.conf
```

### PHP

```sh
sudo cp -i /usr/local/etc/php.ini-production /usr/local/etc/php.ini
```

Run `php --ini | grep Loaded` and check if that says `/usr/local/etc/php.ini`

### phpMyAdmin

Install packages:

```sh
sudo pkg install phpMyAdmin5-php80 php80-iconv
```

Keep a backup of the default config (which is basically empty) and use the sample one as a base for our changes:

```sh
sudo cp /usr/local/www/phpMyAdmin/config.inc.php /usr/local/www/phpMyAdmin/config.inc.php.bak
sudo cp /usr/local/www/phpMyAdmin/config.sample.inc.php /usr/local/www/phpMyAdmin/config.inc.php
```

Now let's edit the config file:

`sudo nano /usr/local/www/phpMyAdmin/config.inc.php`

Find this line:

```
$cfg['Servers'][$i]['AllowNoPassword'] = false;
```

Add this after the line:

```
$cfg['Servers'][$i]['host'] = '127.0.0.1';
```

You can also add this so that it does not logout so often:

```
$cfg['ExecTimeLimit'] = 0;
```

To enable and start mysql/mariadb service:

```
echo 'mysql_enable="YES"' | sudo tee -a /etc/rc.conf
sudo service mysql-server start
```

Now we need to set a password for our root user, otherwise we won't be able to login to phpMyAdmin:

```sh
sudo mariadb-secure-installation
```

Enter these choices:

```
[enter] (current password)
[enter] (unix_socket)
[enter] (change root password)
# give a root password for mariadb - remember to note it down
[enter] (remove anon users)
[enter] (disallow remote root login)
[enter] (remove test db)
[enter] (reload privilege)
```

If you have some trouble, maybe these can help, but probably not needed. I found them while searching for solutions to other issues and thought to keep it around:

```
sudo rm -rf /var/db/mysql/*
sudo cp /usr/local/etc/mysql/conf.d/server.cnf.sample /usr/local/etc/mysql/conf.d/server.cnf
```

## Step 4: Convenience

Add yourself to `www` group and change the permissions so that you can write files without switching to other user every time:

```
sudo pw group mod www -m $USER
# confirm with:
groups $USER
# to allow your normal user to write files
sudo chown -R $USER:$USER /usr/local/www/apache24/data/
```

If you want to put your content directly on `~/www`:

```sh
ln -s /usr/local/www/apache24/data/ ~/www
```


## Info: Directories/Files

- Apache public dir: `/usr/local/www/apache24/data/`
- Apache config: `/usr/local/etc/apache24/httpd.conf`
- Apache https config: `/usr/local/etc/apache24/Includes/httpd-ssl.conf`
- Apache custom config: `/usr/local/etc/apache24/Includes/10-mychanges.conf`
- Mariadb database files path: `/var/db/mysql/`
- phpMyAdmin path: `/usr/local/www/phpMyAdmin/`


**Ref:**
- [FreeBSD Documentation on Apache HTTP Server](https://docs.freebsd.org/en_US.ISO8859-1/books/handbook/network-apache.html)
- [FreeBSD 10: Installing Apache 2.4, MySQL 5.5, and PHP5.5 — Missing libphp5.so](http://blog.ataboydesign.com/2014/04/17/freebsd-10-installing-apache-2-4-mysql-5-5-and-php5-5-missing-libphp5-so/)
